import axios from "axios";
import { message } from "ant-design-vue";
import router from "../router";
const defaultHttp = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL + "/api",
  timeout: 5000,
});

defaultHttp.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      config.headers.Authorization = localStorage.getItem('token');
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

defaultHttp.interceptors.response.use(
  (response) => {
    if (response.data.code == 1) {
      message.error({
        duration: 2,
        content: response.data.message,
      });
      return Promise.reject(response.data.message);
    }
    else if (response.data.code == 401) {
      localStorage.clear();
      message.error({
        duration: 1,
        content: "登录过期，请重新登录",
      });
      router.replace('/login');
    }
    return response.data;
  },
  (error) => {
    if (error.message.includes("timeout")) {
      message.error({
        duration: 2,
        content: "接口请求超时,请刷新页面重试!",
      });
    }
    return Promise.reject(error);
  }
);

export default defaultHttp;
